import moment from 'moment';
import $ from 'jquery';
import { DefaultConfig } from '../common/plug-config';
import { AirConfiguration } from '../common/types';
import sendEmailToMyEmail from '../utils/email';
import { sendMessage } from '../utils/message-send-service';

interface FlightCityInfo {
    time: moment.Moment
    place: string
}
interface AirTicket {
    flightNo: string
    type: string[]
    isCanBuy: boolean
    startInfo: FlightCityInfo
    arriveInfo: FlightCityInfo
}
function getFormatMoment(time: string) {
    return moment(time, 'HH:mm');
}

function sendTableDataUpdate(data: AirTicket[], intervalTime: number) {

    const showData = data.map((item) => ({
        no: `${item.flightNo}`,
        range: `${item.startInfo.place.substring(0, 3)}-${item.arriveInfo.place.substring(0, 3)}`,
        time: `${item.startInfo.time.format('HH:mm')}-${item.arriveInfo.time.format('HH:mm')}`,
        isCanBuy: item.isCanBuy ? '是' : '否',
    }))
    console.table(showData);
    sendMessage({ tableData: showData, intervalTime, }, onRefreshTask)

}
function seekTickRange(airline: AirTicket, searchScope: AirConfiguration['searchScope']) {
    let inRange = airline.isCanBuy;
    if (!inRange) {
        return false;
    }
    inRange = airline.startInfo.time.isBetween(moment(searchScope[0], 'HH:mm'), moment(searchScope[1], 'HH:mm'), 'h', '[]');
    return inRange && tempSeekTickAddress(airline);
}
function tempSeekTickAddress(airline: AirTicket) {
    console.log('airline', airline, !airline.flightNo.includes('HO') && airline.startInfo.place.includes('虹桥'));
    // return !airline.flightNo.includes('HO') && airline.startInfo.place.includes('虹桥');
    return !airline.flightNo.includes('HO');

}
function watchTicketChange() {
    if ($(".booking-select").text() === "") {
        setTimeout(watchTicketChange, 500);
    } else {
        let airlinesDom = $(".booking-select .flight")
        const airlines: AirTicket[] = [];
        airlinesDom.each(function () {
            const summary = $(this).children('.summary');
            const summaryTitle = summary.children(".title");
            summaryTitle.children('img').remove();
            summaryTitle.children('span:first').remove();
            // 不需要共享飞机 中转飞机
            if (!summaryTitle.children('div').children('.blue').length && !summary.text().includes('中转')) {
                const summaryTitleArr = summaryTitle.text().split('|');
                const summaryInfoArr = summary.children('.info').children('.airport');
                const detail = $(this).find('.price.economy');
                let startInfo: FlightCityInfo, arriveInfo: FlightCityInfo;
                summaryInfoArr.each(function (index, element) {
                    const time = $(element).children('time').text();
                    const place = $(element).prop("lastChild").nodeValue;
                    if (index === 0) {
                        startInfo = { time: getFormatMoment(time), place };
                    }
                    if (index === 1) {
                        arriveInfo = { time: getFormatMoment(time), place };
                    }
                });
                airlines.push({
                    flightNo: summaryTitleArr[1].substring(summaryTitleArr[1].indexOf('M')),
                    type: summaryTitleArr.filter((item, index) => index > 1 && item !== ""),
                    isCanBuy: !!detail.text(),
                    startInfo: startInfo!,
                    arriveInfo: arriveInfo!,
                });
            }
        });
        chrome.storage.local.get(['options'], function ({ options }) {
            console.log('content-script用户配置：', options);
            const { searchScope, intervalTime } = options || DefaultConfig;
            if (airlines.length !== 0 &&
                airlines.some((airline) => seekTickRange(airline, searchScope))) {
                chrome.runtime.sendMessage({ type: 'hasTicket' }, function (res) {
                    console.log('找到票票了！！');
                    options.emailMessage && sendEmailToMyEmail();
                });
                console.log('找到机票啦~~');
            } else {

                // refreshTaskTimeoutId = setTimeout(onRefreshTask, intervalTime);
            }
            sendTableDataUpdate(airlines, intervalTime);
        });
    }
}
function getRefreshBtn() {
    return $('#btn_flight_search');
}


export function onRefreshTask(data: any) {
    let retryTimes = 0;
    let refreshTaskTimeoutId = 0;
    if (data && data.cmd === 'refresh') {
        console.log('onRefreshTask');
        (function limit_onRefreshTask() {
            const btn = getRefreshBtn();
            if (btn) {
                clearTimeout(refreshTaskTimeoutId);
                btn.trigger("click");
            } else {
                retryTimes += 1;
                refreshTaskTimeoutId = retryTimes < 5 ? window.setTimeout(limit_onRefreshTask, 500) : 0;
            }
        })()
        console.log('finish~~~~~~~')
    }


}
/**
 * 伪装页面
 */
export function CamouflageWebPage() {
    const headDom = $('head');
    const titleDom = headDom.children('title');
    titleDom.text('哈喽~~');
    const href = chrome.runtime.getURL('img/CIcon.png');
    headDom.append(`<link rel="icon" href="${href}" type="image/x-icon">`);

}
export default watchTicketChange;